package com.atguigu.controller;

import com.atguigu.common.R;
import com.atguigu.entity.Category;
import com.atguigu.entity.Dish;
import com.atguigu.dto.DishDto;
import com.atguigu.entity.DishFlavor;
import com.atguigu.service.impl.CategoryServiceImpl;
import com.atguigu.service.impl.DishFlavorServiceImpl;
import com.atguigu.service.impl.DishServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Resource
    private DishServiceImpl dishService;
    @Resource
    private DishFlavorServiceImpl dishFlavorService;
    @Resource
    private CategoryServiceImpl categoryService;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品,同时保存对应的口味数据
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> addFood(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        //删除当前分类的缓存
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        //向数据库保存客户端新增的菜品
        LambdaUpdateWrapper<Dish> dishLambdaUpdateWrapper = new LambdaUpdateWrapper<Dish>();
        dishLambdaUpdateWrapper.setEntity(dishDto);

        dishService.saveWithDishFalvor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品列表分页
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page=" + page + ",pageSize=" + pageSize + ",name=" + name);
        //
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null, Dish::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(dishPage, queryWrapper);

        //将dishPage中除记录外的所有信息拷贝到dishDtoPage中
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        //遍历dishPage中的每条Dish记录，并拷贝到新的DishDto中
        List<Dish> records = dishPage.getRecords();
        ArrayList<DishDto> dishDtos = new ArrayList<>();
        for (Dish dish : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);

            //利用CateServiceImpl的categoryId查找对应的category,获取相应的categoryName
            Category category = categoryService.getById(dish.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }

            //将dishDto加入到dishDtos集合中
            dishDtos.add(dishDto);
        }
        //将dishDtos放入dishDtoPage
        dishDtoPage.setRecords(dishDtos);


        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getDish(@PathVariable("id") String id) {
        log.info(id);
        //重现菜品信息
        DishDto dishDto = dishService.queryDishDto(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        //删除当前分类的缓存
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        dishService.updateDishDto(dishDto);
        return R.success("修改菜品成功");
    }

    /**
     * 根据条件查询菜品信息
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        log.info(dish.toString());
        //从redis中获取数据
        List<DishDto> dishDtoList =null;
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);
        //如果从redis中能够查询到相应的数据，直接返回查询到的结果
        if(dishDtoList!=null){
            return R.success(dishDtoList);
        }
        //否则从MySQL数据库中查询，并将查询到的数据存储到redis中
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据categoryId获取dish记录
        dishLambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //排序
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //获取状态为1（起售）的dish
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
        //获取dish集合
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        //将dish集合保存到redis中

        redisTemplate.opsForValue().set(key,list);
        //将dish集合转化成为DishDto集合
        dishDtoList = new ArrayList<>();
        for (Dish dish1 : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1,dishDto);


            //获取分类名称
            Category category = categoryService.getById(dish.getCategoryId());
            dishDto.setCategoryName(category.getName());
            //获取每个菜品的口味数据
            Long dish1Id = dish1.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dish1Id);
            List<DishFlavor> dishFlavorList= dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            dishDtoList.add(dishDto);
        }

        //将从MySQL数据库中查询到的结果储存到redis中,过期时间60min
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

}
